Having a confusing time witgh regex here. I'me trying to split a string by new lines and then by semicolons. The code I wrote is bellow:
string txt1 = "one;two;three;four;five;six;seven\neight;nine;ten;eleven;twelve;thirteen;fourteen\nfifteen;sixteen;seventeen;eighteen;nineteen;twenty;twenty-one"
Regexp line = regexp2 ".+"
Regexp splitDetails = regexp2 "[^;]+";
string aLine = "";
while (!null txt1 && line(txt1)) {
aLine = txt1[match 0];
print "Line: " aLine "\n";
if(splitDetails(aLine)) {
print "Match 0: " aLine[match 0] "\n";
print "Match 1: " aLine[match 1] "\n";
print "Match 2: " aLine[match 2] "\n";
print "Match 3: " aLine[match 3] "\n";
print "Match 4: " aLine[match 4] "\n";
print "Match 5: " aLine[match 5] "\n";
print "Match 6: " aLine[match 6] "\n\n";
}
txt1 = txt1[end 0 + 2:] // move past newline
}
Following below is the output that I'm expecting but I'm not getting that. Anyone know what I'm doing wrong?
Line: one;two;three;four;five;six;seven
Line: eight;nine;ten;eleven;twelve;thirteen;fourteen
Line: fifteen;sixteen;seventeen;eighteen;nineteen;twenty;twenty-one
Mr 4D - Wed May 30 05:15:05 EDT 2018 |
Re: Confusing regex If you want to use [match 1] to match[6] then you need 6 pairs of brackets in your regex. Match 0 is always "everything the regex found", Match 1 is the content of the text inside the first brackets, Match 2 of the second etc. I see two options here: 1. you know that you always have 6 matches, then you create a regex with 6 pairs of brackets like "([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)" and you can use the rest of your code "as-is" (well kind of, you need to change a few things since you currently want to find pairs of 7 and not 6, but you can't use match 0 for that). This will fail if you end up with a amount of entries that is not clearly dividable by 6 (see what happens with twenty-one when you run your code with the modified regex). 2. you modify the regex to find a single match and then use it in a while loop by removing the latest match like you do in line 22 already (txt1[end 0 + 2:]) and then only check match 0. This is probably the cleaner solution. |